package com.tomecode.tools.maven.settings.util;

import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * url tester (connection timeout)
 * 
 * @author Frastia Tomas
 * 
 */
public final class URLTester {

	public static final int TIME_OUT_SECONDS = 30 * 1000;
	// private URLConnection connection = null;
	private final URL url;
	private volatile Thread t = null;

	private volatile boolean isCancel = false;

	public URLTester(URL _url) {
		this.url = _url;
	}

	/**
	 * spustenie testovania pripojenia
	 * 
	 * @param timeout
	 * @throws java.net.ConnectException
	 */
	public synchronized void testConnection(int timeout) throws ConnectException {
		TesterThread testerThread = new TesterThread();
		t = new Thread(testerThread);
		t.start();

		try {
			this.wait(timeout);
		} catch (InterruptedException e) {
		}

		t.interrupt();

		if (isCancel) {
			return;
		}

		if (!testerThread.isOpened) {
			throw new ConnectException("Connection timed out");
		}
	}

	/**
	 * 
	 * @author Frastia Tomas tomas_frastia@tempest.sk
	 */
	private final class TesterThread implements Runnable {

		private volatile boolean isOpened = false;

		private TesterThread() {
		}

		public final void run() {
			URLConnection con = null;
			try {
				con = url.openConnection();
				con.getInputStream();
				isOpened = true;
				synchronized (URLTester.this) {
					URLTester.this.notify();
				}

			} catch (Exception e) {

			} finally {
				close(con);
			}

		}
	}

	/**
	 * zatvorenie spojenia so serverom
	 * 
	 * @param con
	 */
	private static final void close(URLConnection con) {
		if (con instanceof HttpURLConnection) {
			((HttpURLConnection) con).disconnect();
		}
		con = null;
	}

	public final void cancel() {
		isCancel = true;
		synchronized (this) {
			this.notify();
		}
	}
}
